package controllers.chat;

import models.chat.Channel;
import models.chat.Member;
import models.chat.Status;
import models.chat.engines.MessageEngine;
import models.chat.messages.system.MemberChangedStatusMessage;
import models.chat.messages.system.MemberJoinedChannelMessage;
import play.mvc.Controller;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Konovalov_Nik
 */
public class ChatController extends Controller {

    public static final String GLOBAL = "Global";
    public static List<Channel> channels;
    public static List<Member> members;
    static volatile long lastId;

    static {
        channels = new ArrayList<Channel>();
        members = new ArrayList<Member>();

        Channel global = new Channel(GLOBAL);
        global.save();
        channels.add(global);

        lastId = members.size();
    }

    public static void index() {
        String uid = session.get("uid");
        Member current;
        List<Member> renderMemberList = new ArrayList<Member>();
        Channel global = Channel.find("byName", GLOBAL).first();
        if (uid == null) {
            lastId++;
            Member newMember = new Member("user" + lastId);
            members.add(newMember);
            current = newMember;
            current.save();
        } else {
            Long id = Long.parseLong(uid);
            current = Member.findById(id);
        }
        session.put("uid", current.id);
        MessageEngine.addMessage(new MemberJoinedChannelMessage(current, global));

        render(current, global);
    }

    public static void listMembers() {
        Channel globalChannel = Channel.find("byName", GLOBAL).first();
        List<Member> members = globalChannel.getMembers();
        render(members);
    }


    public static void renameMember(String newName) {
        String uid = session.get("uid");
        Member current = Member.findById(Long.parseLong(uid));
        current.name = newName;
        current.save();
    }

    public static void changeStatus(String status) {
        String uid = session.get("uid");
        Member current = Member.findById(Long.parseLong(uid));
        current.status = Status.valueOf(status);
        MessageEngine.addMessage(new MemberChangedStatusMessage(current));
        current.save();
    }
}
